﻿using System;
using System.Collections.Generic;

namespace FlashPay.Service.Impl
{
    using FlashPay.DAO.Interface;
    using FlashPay.Service.Interface;

    using FlashPay.EF.Models;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity;
    using FlashPay.Entity.Response.Role;
    using FlashPay.Util;
    using FlashPay.Entity.Request.Role;
    using System.Linq;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Request.Authorize;
    using FlashPay.Entity.Response.Company;
    using Newtonsoft.Json;
    using FlashPay.EF;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 角色业务接口实现
    /// </summary>
    public class SysRoleServiceImpl:SysRoleService
    {
        #region 注入
        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly SysRoleDao _sysRole;

        /// <summary>
        /// 菜单数据接口
        /// </summary>
        private readonly MenuDao _menuDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 菜单权限关联数据接口
        /// </summary>
        private readonly MenuPermissionDao _menuPermissionDao;

        /// <summary>
        /// 授权数据接口
        /// </summary>
        private readonly AuthorizeDao _authorizeDao;

        /// <summary>
        /// 角色数据接口
        /// </summary>
        private readonly UserRoleDao _userRoleDao;

        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly UserInfoDao _userInfoDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PermissionDao _permissionDao;

        /// <summary>
        /// 
        /// </summary>
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="sysRole">角色数据接口</param>
        /// <param name="menuDao">菜单数据接口</param>
        /// <param name="companyDao">公司数据接口</param>
        /// <param name="menuPermissionDao">菜单权限关联数据接口</param>
        /// <param name="authorizeDao">授权数据接口</param>
        public SysRoleServiceImpl(SysRoleDao sysRole, MenuDao menuDao, CompanyDao companyDao, MenuPermissionDao menuPermissionDao, AuthorizeDao authorizeDao, UserRoleDao userRoleDao, UserInfoDao userInfoDao, LogDao logDao, LogRecord logRecord, PermissionDao permissionDao, IHttpContextAccessor accessor, FlashPayContext context)
        {
            _sysRole = sysRole;
            _menuDao = menuDao;
            _companyDao = companyDao;
            _menuPermissionDao = menuPermissionDao;
            _authorizeDao = authorizeDao;
            _userRoleDao = userRoleDao;
            _userInfoDao = userInfoDao;
            _logDao = logDao;
            _logRecord = logRecord;
            _permissionDao = permissionDao;
            _accessor = accessor;
            _context = context;
        }
        #endregion

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public RoleResponse Get(int id)
        {
            var model = _sysRole.Get(id, _context);


            var roleResponse = new RoleResponse()
            {
                RId = model.RId,
                RCompanyId = model.RCompanyId,
                RName = model.RName,
                CreateDate = model.CreateDate,
                RStatus = model.RStatus,
                CreateCId = model.CreateCid
            };

            var company = _menuDao.GetById(model.RCompanyId);
            if (company != null) {
                roleResponse.CompanyName = company.CompanyName;
            }
            if (model != null) {

                var companyResponses = new List<CompanyResponse>();

                #region 查询公司信息
                var companys = GetCompany(model.RCompanyId, 2);

                if (companys !=null && companys.Any()) {
                    foreach (var item in companys)
                    {
                        companyResponses.Add(new CompanyResponse()
                        {
                            CompanyID = item.CompanyID,
                            CompanyName = item.CompanyName,
                        });
                    }
                }
                #endregion

                roleResponse.CompanyResponse = companyResponses;
            }

            return roleResponse;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public RoleResponse GetClone(int companyId,int id)
        {
            var model = _sysRole.Get(id, _context);


            var roleResponse = new RoleResponse()
            {
                RId = model.RId,
                RCompanyId = model.RCompanyId,
                RName = model.RName,
                CreateDate = model.CreateDate,
                RStatus = model.RStatus,
                CreateCId = model.CreateCid
            };

            var company = _menuDao.GetById(model.RCompanyId);
            if (company != null)
            {
                roleResponse.CompanyName = company.CompanyName;
            }
            if (model != null)
            {

                var companyResponses = new List<CompanyResponse>();

                #region 查询公司信息
                var companys = GetCompany(companyId, 2);

                if (companys != null && companys.Any())
                {
                    foreach (var item in companys)
                    {
                        companyResponses.Add(new CompanyResponse()
                        {
                            CompanyID = item.CompanyID,
                            CompanyName = item.CompanyName,
                        });
                    }

                    companyResponses.RemoveAll(p => p.CompanyID == model.RCompanyId);
                }
                #endregion

                roleResponse.CompanyResponse = companyResponses;
            }

            return roleResponse;
        }


        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public List<CompanyResponse> GetCompany(int companyId,int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus=item.CompanyStatus
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 比对
        /// </summary>
        /// <param name="oldAuthorizes">当前公司下级子公司所有授权记录(不包括当前公司)</param>
        /// <param name="newAuthorizes">修改的当前授权记录</param>
        private void DeleteAuthorize(RoleRequest request,List<AuthorizeRequest> unselectedAuthorizes, FlashPayContext _context) {

            //获取当前公司下的所有角色
            var companyIds = request.CompanyIds;

            //获取子公司所有角色
            var roleIds = _sysRole.GetByCompanyIds(companyIds, _context).Select(p => p.RId).ToList();

            //获取子公司所有角色菜单权限
            var unselectedMenuPIds = unselectedAuthorizes.Where(p=>p.AuthType == AuthorizeType.菜单.GetHashCode()).Select(p => p.AuthPid).ToList();
            //获取子公司所有角色功能权限
            var unselectedPermissionPIds = unselectedAuthorizes.Where(p => p.AuthType == AuthorizeType.权限.GetHashCode()).Select(p => p.AuthPid).ToList();

            var deleteAuthIds = new List<int>();

            //当前公司的子公司所有授权
            if (unselectedMenuPIds != null && unselectedMenuPIds.Any()) {
                var authorizesMenu = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedMenuPIds, AuthorizeType.菜单.GetHashCode(), _context);
                if (authorizesMenu != null && authorizesMenu.Any())
                {
                    foreach (var item in authorizesMenu)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }

            if (unselectedPermissionPIds != null && unselectedPermissionPIds.Any()) {
                var authorizesPermission = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedPermissionPIds, AuthorizeType.权限.GetHashCode(), _context);

                if (authorizesPermission != null && authorizesPermission.Any())
                {
                    foreach (var item in authorizesPermission)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }


            if (deleteAuthIds != null && deleteAuthIds.Any()) {
                _authorizeDao.DeleteByAuthId(deleteAuthIds, _context);
            }
        }

        /// <summary>
        /// 删除内部删除
        /// </summary>
        private void DeleteInnerAuthorize(int companyId, List<AuthorizeRequest> unselectedAuthorizes, FlashPayContext _context)
        {
            //获取当前公司下的所有子公司
            var companys = this.GetCompany(companyId, 5);

            var roleIds = new List<int>();

            if (companys != null && companys.Any()) {
                companys.ForEach(item => {
                    //角色为内部账号的时候过滤自己，避免在添加内部账号其它账户的角色
                    if (item.CompanyID != companyId)
                    {
                        var sysRoleList = _sysRole.GetRoleByCompanyId(item.CompanyID, _context);
                        if (sysRoleList != null && sysRoleList.Any())
                        {
                            sysRoleList.ForEach(roleItme => {
                                roleIds.Add(roleItme.RId);
                            });
                        }
                    }
                });
            }

            //删除的菜单权限和功能权限列表
            var unselectedMenuPIds = unselectedAuthorizes.Where(p => p.AuthType == AuthorizeType.菜单.GetHashCode()).Select(p => p.AuthPid).ToList();
            var unselectedPermissionPIds = unselectedAuthorizes.Where(p => p.AuthType == AuthorizeType.权限.GetHashCode()).Select(p => p.AuthPid).ToList();

            var deleteAuthIds = new List<int>();

            //当前公司的子公司所有授权
            if (unselectedMenuPIds != null && unselectedMenuPIds.Any())
            {
                var authorizesMenu = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedMenuPIds, AuthorizeType.菜单.GetHashCode(), _context);
                if (authorizesMenu != null && authorizesMenu.Any())
                {
                    foreach (var item in authorizesMenu)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }

            if (unselectedPermissionPIds != null && unselectedPermissionPIds.Any())
            {
                var authorizesPermission = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedPermissionPIds, AuthorizeType.权限.GetHashCode(), _context);

                if (authorizesPermission != null && authorizesPermission.Any())
                {
                    foreach (var item in authorizesPermission)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }

            if (deleteAuthIds != null && deleteAuthIds.Any())
            {
                _authorizeDao.DeleteByAuthId(deleteAuthIds, _context);
            }
        }

        /// <summary>
        /// 删除内部删除
        /// </summary>
        private void DeleteInner(int roleId,int companyId,List<AuthorizeRequest> unselectedAuthorizes, FlashPayContext _context)
        {
            //获取当前公司下的所有子公司
            //var companys = this.GetCompany(companyId, 5);
            var currentRoleUserInfos = _sysRole.GetRoleByUserId(roleId, companyId);

            //获取所有用户
            var userInfoAll = _userInfoDao.GetList(new UserInfoQuery() { });
            //查询当前用户下级所有用户
            var userInfos = GetChildUsers(userInfoAll, new List<UserInfo>() { }, currentRoleUserInfos);
            if (userInfos == null || userInfos.Count <= 0)
            {
                return;
            }
            var userIds = userInfos.Select(c => c.UId).ToList();
            //获取角色
            var roleIds = _sysRole.GetRoleByCreateIdAndCompanyId(companyId,userIds, _context).Select(c=>c.RId).ToList();
            if (roleIds==null && roleIds.Count<=0) {
                return;
            }
            //删除的菜单权限和功能权限列表
            var unselectedMenuPIds = unselectedAuthorizes.Where(p => p.AuthType == AuthorizeType.菜单.GetHashCode()).Select(p => p.AuthPid).ToList();
            var unselectedPermissionPIds = unselectedAuthorizes.Where(p => p.AuthType == AuthorizeType.权限.GetHashCode()).Select(p => p.AuthPid).ToList();

            var deleteAuthIds = new List<int>();

            //当前公司的子公司所有授权
            if (unselectedMenuPIds != null && unselectedMenuPIds.Any())
            {
                var authorizesMenu = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedMenuPIds, AuthorizeType.菜单.GetHashCode(), _context);
                if (authorizesMenu != null && authorizesMenu.Any())
                {
                    foreach (var item in authorizesMenu)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }

            if (unselectedPermissionPIds != null && unselectedPermissionPIds.Any())
            {
                var authorizesPermission = _authorizeDao.GetPermissionByRoleSysNo(roleIds, unselectedPermissionPIds, AuthorizeType.权限.GetHashCode(), _context);

                if (authorizesPermission != null && authorizesPermission.Any())
                {
                    foreach (var item in authorizesPermission)
                    {
                        deleteAuthIds.Add(item.AuthId);
                    }
                }
            }

            if (deleteAuthIds != null && deleteAuthIds.Any())
            {
                _authorizeDao.DeleteByAuthId(deleteAuthIds, _context);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="all"></param>
        /// <param name="returnUserInfos"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        private List<UserInfo> GetChildUsers(List<UserInfo> list, List<UserInfo> infos,List<UserInfo> currentRoleUserInfos)
        {
            foreach (var item in currentRoleUserInfos) {

                infos.Add(item);

                var userInfos = list.Where(c => c.UCreateId == item.UId).ToList();
                if (userInfos != null && userInfos.Any())
                {
                    infos.AddRange(userInfos);
                    foreach (var childItem in userInfos)
                    {
                        var childUserInfos = list.Where(c => c.UCreateId == childItem.UId).ToList();
                        if (childUserInfos != null && childUserInfos.Any()) {
                            infos.AddRange(childUserInfos);
                        }
                    }
                }
            }

            return infos;
        }



        #region 角色保存或修改
        /// <summary>
        /// 角色保存或修改
        /// </summary>
        /// <returns></returns>
        public JResult<SysRole> SaveOrEdit(RoleRequest request, List<AuthorizeRequest> editAuthorizes, List<AuthorizeRequest> unselectedAuthorizes)
        {
            var result = new JResult<SysRole>()
            {
                Success = false
            };

            //模型转换
            var role = new SysRole()
            {
                RId = request.RId,
                RCompanyId = request.RCompanyId,
                RName = request.RName,
                CreateDate = request.CreateDate,
                RStatus = request.RStatus,
                CreateCid = request.CreateCid,
                CreateUid = request.CreateUid
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    if (role.RId > 0)
                    {
                        #region 修改
                        var model = _sysRole.Get(role.RId, _context);
                        var json = JsonConvert.SerializeObject(model);
                        //验证当前公司下是否有相同的角色名称(排除自己)
                        var query = new SysRoleQuery()
                        {
                            NoEqualRId = model.RId,
                            CompanyId = model.RCompanyId,
                            RName = role.RName
                        };
                        var nameExist = _sysRole.GetList(query, _context);
                        if (nameExist != null && nameExist.Any())
                        {
                            throw new Exception("角色名称已存在！");
                        }
                        //删除角色授权信息
                        _authorizeDao.DeleteByRoleSysNo(role.RId, _context);

                        #region 批量插入授权信息
                        if (editAuthorizes != null && editAuthorizes.Any())
                        {
                            editAuthorizes.ForEach(item =>
                            {
                                _authorizeDao.Add(new Authorize()
                                {
                                    AuthRid = item.AuthRid,
                                    AuthPid = item.AuthPid,
                                    AuthType = item.AuthType,
                                    CreateDate = DateTime.Now
                                }, _context);
                            });
                        }
                        #endregion

                        var updateStatus = _sysRole.Update(role, _context);
                        if (updateStatus.Success)
                        {
                            #region //日志
                            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                            _logRecord.LogType = LogRecordLogType.Role_Update.GetHashCode();
                            _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                            _logRecord.CreateDate = DateTime.Now;
                            _logRecord.LogRemark = string.Format("编辑角色,角色编号:{0}", role.RId);
                            _logRecord.RequestData = JsonConvert.SerializeObject(unselectedAuthorizes);
                            _logRecord.AffectData = JsonConvert.SerializeObject(editAuthorizes);
                            _logDao.Insert(_logRecord);
                            #endregion

                            //子公司权限
                            if (model.CreateCid == request.CreateCid && unselectedAuthorizes!=null && unselectedAuthorizes.Any())
                            {
                                if (model.RCompanyId == request.CreateCid)
                                {
                                    DeleteInner(model.RId, model.RCompanyId,unselectedAuthorizes, _context);
                                }
                                else {
                                    if (request.CompanyIds != null && request.CompanyIds.Any()) {

                                        DeleteAuthorize(request, unselectedAuthorizes, _context);

                                        DeleteInnerAuthorize(model.RCompanyId, unselectedAuthorizes, _context);
                                    }
                                }
                                
                            }

                            result.Success = true;
                            tran.Commit();
                        }
                        else
                        {
                            throw new Exception(string.Format("编辑角色失败,角色编号:{0}", role.RId));
                        }
                        #endregion
                    }
                    else
                    {
                        #region 新增
                        //验证当前公司下是否有相同的角色名称
                        var query = new SysRoleQuery()
                        {
                            CompanyId = role.RCompanyId,
                            RName = role.RName
                        };
                        var nameExist = _sysRole.GetList(query,_context);
                        if (nameExist != null && nameExist.Any())
                        {
                            throw new Exception("角色名称已存在！");
                        }

                        var addResult = _sysRole.Add(role,_context);
                        if (addResult.Success && addResult.Data.RId > 0)
                        {
                            //批量插入授权信息
                            if (editAuthorizes != null && editAuthorizes.Any())
                            {
                                editAuthorizes.ForEach(item =>
                                {
                                    _authorizeDao.Add(new Authorize()
                                    {
                                        AuthRid = addResult.Data.RId,
                                        AuthPid = item.AuthPid,
                                        AuthType = item.AuthType,
                                        CreateDate = DateTime.Now
                                    },_context);
                                });
                            }

                            //日志
                            var affectData = new
                            {
                                before = new
                                {

                                },
                                after = new
                                {
                                    SysRole = addResult.Data
                                }
                            };
                            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                            _logRecord.LogType = LogRecordLogType.Role_Add.GetHashCode();
                            _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                            _logRecord.CreateDate = DateTime.Now;
                            _logRecord.LogRemark = string.Format("新增角色,角色名称:{0}", role.RName);
                            _logRecord.RequestData = JsonConvert.SerializeObject(unselectedAuthorizes);
                            _logRecord.AffectData = JsonConvert.SerializeObject(editAuthorizes);
                            _logDao.Insert(_logRecord);

                            result.Success = true;
                            tran.Commit();
                        }
                        else
                        {
                            throw new Exception(string.Format("新增角色失败,角色名称:{0}", role.RName));
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        tran.Rollback();
                        //日志
                        _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                        _logRecord.LogType = role.RId > 0 ? LogRecordLogType.Role_Update.GetHashCode() : LogRecordLogType.Role_Add.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("{0}角色失败：", role.RId > 0 ? "编辑" : "新增") + ex.Message;
                        _logDao.Insert(_logRecord);

                        result.ErrorMessage = ex.Message;
                    }
                    catch
                    {
                        result.ErrorMessage = ex.Message;
                    }
                }
            }
            
            return result;
        }
        #endregion

        #region 更新状态
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, SByte status)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                if (_sysRole.UpdateStatus(id, status))
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.Role_Update.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新状态角色状态成功,角色编号：{0},状态值：{1}", id, status);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex) {
                try
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.Role_Update.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新状态角色状态失败,角色编号:{0},{1}", id,ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public JResult Delete(int id)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                //数据验证
                var userRoles = _userRoleDao.GetByRoleId(id);
                if (userRoles != null && userRoles.Any()) {
                    result.ErrorMessage = "删除失败,此角色已使用中！";
                    return result;
                }
                var deleteUserRoleStatus = _userRoleDao.DeleteByroleRId(id);
                if (deleteUserRoleStatus)
                {
                    //删除
                    var deleteRoleStatus = _sysRole.Delete(id);
                    if (deleteRoleStatus)
                    {
                        //日志
                        _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                        _logRecord.LogType = LogRecordLogType.UserRole_Delete.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("删除角色成功,角色编号:{0}", id);
                        _logDao.Insert(_logRecord);

                        result.SuccessMessage = "删除成功！";
                        result.Success = true;
                    }

                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.UserRole_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("删除角色失败,角色编号:{0},{1}", id, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch {

                }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        /// <summary>
        /// 根据条件获取所有角色记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<SysRole></returns>
        public List<SysRole> GetList(SysRoleQuery query)
        {
            return _sysRole.GetList(query);
        }

        /// <summary>
        /// 获取公司角色编号
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<UserInfo></returns>
        public List<SysRole> GetRoleByCompanyId(SysRoleQuery query)
        {
            return _sysRole.GetRoleByCompanyId(query);
        }

        #region 获取角色菜单权限树
        /// <summary>
        /// 获取角色菜单权限树
        /// </summary>
        /// <param name="roleSysNo">角色编号</param>
        /// <returns>角色菜单权限树列表</returns>
        public List<ZCheckTreeNodeResponse> GetMenuPermissionViewListByRoleSysNo(List<String> userPermission,int mType, int roleSysNo,int userId)
        {
            //菜单列表
            var menuList = _menuDao.GetList(new Entity.Request.Menu.MenuQueryRequest() {
            MType = mType
            });
            //菜单权限列表
            var menuPermissionViewList = _menuPermissionDao.GetMenuPermissionViewList();
            //获取已选择菜单权限列表
            var authorizes = _authorizeDao.GetPermissionListRoleSysNo(roleSysNo);


            var zCheckTreeNodes = new List<ZCheckTreeNodeResponse>();

            menuList.ForEach(item => {
                //菜单
                var zCheckTreeNode = new ZCheckTreeNodeResponse();
                zCheckTreeNode.id = string.Format("m_{0}", item.Mid);
                zCheckTreeNode.pId = string.Format("m_{0}", item.MParent);
                zCheckTreeNode.name = item.MName;
                zCheckTreeNode.nodetype = AuthorizeType.菜单.GetHashCode();
                zCheckTreeNode.@checked = authorizes.Any(authorize => authorize.AuthType == AuthorizeType.菜单.GetHashCode() && authorize.AuthPid == item.Mid);
                //zCheckTreeNode.@checked || userPermission.Contains(item.Mid.ToString()) || userPermission.Contains("plashPay"))
                if (zCheckTreeNode.@checked || userPermission.Contains("MM"+item.Mid.ToString()) || userPermission.Contains("plashPay"))
                {
                    zCheckTreeNodes.Add(zCheckTreeNode);
                    //功能权限
                    var menuPermissionList = menuPermissionViewList.Where(menuItem => menuItem.MpMid.Equals(item.Mid) && menuItem.Hide == PermissionStatus.显示.GetHashCode()).OrderBy(p=>p.SortNo).ToList();
                    if (menuPermissionList != null && menuPermissionList.Any())
                    {
                        menuPermissionList.ForEach(p =>
                        {
                            var childZCheckTreeNode = new ZCheckTreeNodeResponse();
                            childZCheckTreeNode.id = string.Format("p_{0}", p.Pid);
                            childZCheckTreeNode.pId = string.Format("m_{0}", item.Mid);
                            childZCheckTreeNode.name = p.PName;
                            childZCheckTreeNode.nodetype = AuthorizeType.权限.GetHashCode();
                            childZCheckTreeNode.@checked = authorizes.Any(authorize => authorize.AuthType == AuthorizeType.权限.GetHashCode() && authorize.AuthPid == p.Pid);
                            if (childZCheckTreeNode.@checked || userPermission.Contains(p.PCode.ToString()) || userPermission.Contains("plashPay"))
                                zCheckTreeNodes.Add(childZCheckTreeNode);
                        });
                    }
                }
            });

            return zCheckTreeNodes;
        }

        /// <summary>
        /// 获取角色菜单权限树
        /// </summary>
        /// <param name="roleSysNo">角色编号</param>
        /// <returns>角色菜单权限树列表</returns>
        public List<ZCheckTreeNodeResponse> GetMenuPermissionViewListByRole(List<String> userPermission, int mType,int userID)
        {
            //菜单列表
            var menuList = _menuDao.GetList(new Entity.Request.Menu.MenuQueryRequest()
            {
                MType = mType
            });
            //菜单权限列表
            var menuPermissionViewList = _menuPermissionDao.GetMenuPermissionViewList();
            //获取已选择菜单权限列表
            var authorizes = _authorizeDao.GetPermissionListRole(userID);


            var zCheckTreeNodes = new List<ZCheckTreeNodeResponse>();

            menuList.ForEach(item => {
                //菜单
                var zCheckTreeNode = new ZCheckTreeNodeResponse();
                zCheckTreeNode.id = string.Format("m_{0}", item.Mid);
                zCheckTreeNode.pId = string.Format("m_{0}", item.MParent);
                zCheckTreeNode.name = item.MName;
                zCheckTreeNode.nodetype = AuthorizeType.菜单.GetHashCode();
                zCheckTreeNode.@checked = false;
                var parentChecked = authorizes.Any(authorize => authorize.AuthType == AuthorizeType.菜单.GetHashCode() && authorize.AuthPid == item.Mid);
                if (parentChecked || userPermission.Contains("plashPay"))
                {
                    zCheckTreeNodes.Add(zCheckTreeNode);
                    //功能权限
                    var menuPermissionList = menuPermissionViewList.Where(menuItem => menuItem.MpMid.Equals(item.Mid) && menuItem.Hide == PermissionStatus.显示.GetHashCode()).OrderBy(p => p.SortNo).ToList();
                    if (menuPermissionList != null && menuPermissionList.Any())
                    {
                        menuPermissionList.ForEach(p =>
                        {
                            var childZCheckTreeNode = new ZCheckTreeNodeResponse();
                            childZCheckTreeNode.id = string.Format("p_{0}", p.Pid);
                            childZCheckTreeNode.pId = string.Format("m_{0}", item.Mid);
                            childZCheckTreeNode.name = p.PName;
                            childZCheckTreeNode.nodetype = AuthorizeType.权限.GetHashCode();
                            childZCheckTreeNode.@checked = false;
                            var childCheck = authorizes.Any(authorize => authorize.AuthType == AuthorizeType.权限.GetHashCode() && authorize.AuthPid == p.Pid);
                            if (childCheck || userPermission.Contains("plashPay"))
                                zCheckTreeNodes.Add(childZCheckTreeNode);
                        });
                    }
                }
            });

            return zCheckTreeNodes;
        }
        #endregion

        #region 分页查询
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<RoleResponse> GetPager(SysRoleQuery query)
        {
            var pager = new PagedList<RoleResponse>() {
                Success = false
            };

            try
            {
                #region 获取当前公司及子公司编号
                //参数赋值
                var companyRequest = new EF.Models.Company()
                {
                    CompanyId = query.CompanyId.Value,
                    CompanyPid = -1,
                    CompanyStatus = 1
                };

                var companyQueryResult = new BaseModel<List<EF.Models.Company>>();
                //查询
                _companyDao.Get(companyQueryResult, companyRequest, 2);
                if (companyQueryResult != null && companyQueryResult.Success)
                {
                    var companyIds = new List<int>();

                    if (companyQueryResult.Result != null && companyQueryResult.Result.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(query.CompanyName))
                        {
                            var companys = companyQueryResult.Result.Where(p => p.CompanyName.Contains(query.CompanyName)).ToList();
                            companys.ForEach(item => {
                                companyIds.Add(item.CompanyId);
                            });
                        }
                        else {
                            companyQueryResult.Result.ForEach(item => {
                                companyIds.Add(item.CompanyId);
                            });
                        }
                    }

                    //移除当前当前编号
                    //companyIds.Remove(query.CompanyId.Value);

                    if (companyIds != null && companyIds.Any()) {
                        query.CompanyIds = companyIds;
                    }
                }
                #endregion

                //获取所有公司信息
                var companylist = _companyDao.Get();

                var rolePager = _sysRole.GetPager(query);
                if (rolePager != null) {

                    var roleResponseList = new List<RoleResponse>();

                    if (rolePager.TData != null) {
                        foreach (var item in rolePager.TData) {

                            var roleResponse = new RoleResponse()
                            {
                                RId = item.RId,
                                RCompanyId = item.RCompanyId,
                                RName = item.RName,
                                CreateDate = item.CreateDate,
                                RStatus = item.RStatus
                            };

                            var company = companylist.Result.FirstOrDefault(p => p.CompanyId == item.RCompanyId);
                            if (company != null) {
                                roleResponse.CompanyName = company.CompanyName;
                            }
                            roleResponseList.Add(roleResponse);
                        }

                        pager.TData = roleResponseList;
                    }
                    pager.CurrentPageIndex = rolePager.CurrentPageIndex;
                    pager.TotalCount = rolePager.TotalCount;
                }
            }
            catch(Exception ex) {
                pager.ErrorMessage = ex.Message;
            }

            return pager;
        }
        #endregion
    }
}
